import axios from 'axios'
import { IPCONFIG } from '@renderer/config'
import API from '@renderer/api/constant'
import _ from 'lodash'
import { useSystemSettingStore } from '@renderer/store/pinia/systemSetting'
import { router } from '@renderer/routers'
import routeConstants from '@renderer/routers/routeConstants'
import { GlobalNotification } from '@renderer/components/Toast/GlobalNotification'

axios.defaults.baseURL = IPCONFIG.baseUrl
axios.defaults.timeout = 60000
let access_token


const axiosInstance = axios.create()


axiosInstance.interceptors.request.use(
  config => {
    // 对于state中
    const store = useSystemSettingStore()
    access_token = store.access_token
    if (access_token) {
      config.headers.Authorization = `bearer ${access_token}`
    }
    if (config.url === API.login) {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      config.transformRequest = [function(data) {
        let ret = ''
        let objKeyArr = Object.keys(data)
        for (let i = 0; i < objKeyArr.length; i++) {
          let it = objKeyArr[i]
          if (i !== objKeyArr.length - 1) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          } else {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
          }
        }
        return ret
      }]
    } else if (config.url === API.submitScan || config.url === API.submitScan4D || config.url === API.submitManualScan) {

    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)


axiosInstance.interceptors.response.use(function(response) {
  const store = useSystemSettingStore()
  if (response.data.access_token) {
    access_token = response.data.access_token
    store.setAccessToken(access_token)
  }
  return response
}, function(error) {
  const store = useSystemSettingStore()
  if (error?.response) {
    switch (error.response.status) {
      case 401:
        store.setAccessToken('')
        access_token = ''
        router.push({
          path: routeConstants.LoginPage.path
        })
        return Promise.reject({
          message: '登录失效'
        })
      case 400:
        return Promise.reject({
          message: '账号密码错误'
        })
      default:
        Promise.reject(error)
        break
    }
  }
  return
})


async function post(url, params: any = null) {
  let paras: any = null
  if (url === API.login) {
    paras = Object.assign({}, params)
  } else {
    paras = params
  }
  const timeout = getTimeout(url)
  return new Promise(async (resolve, reject) => {
    try {
      const res = await axiosInstance.post(url, paras, {
        timeout
      })
      resolve(res.data)
    } catch (e) {
      reject(e)
    }
  })
}

function getTimeout(url) {
  const timeout60 = [API.submitScan, API.submitScan4D]
  if (timeout60.includes(url)) {
    return 60 * 1000
  } else {
    return 60 * 1000
  }
}

const postWithAns = _.debounce(async (api: string, successHandler: any = null, params: any = {}, errorHandler: any = (msg: string) => {
  GlobalNotification({
    title: 'Error',
    message: msg,
    type: 'error'
  })
}) => {
  return new Promise(async (resolve, reject) => {
    try {
      const res: any = await post(api, params)
      if (res.code === 1) {
        if (successHandler) {
          await successHandler(res.data)
        }
        resolve(res.data)
      } else {
        if (errorHandler) {
          errorHandler(res.msg)
        }
        reject(res.data)
      }
    } catch (e: any) {
      reject(e)
      if (errorHandler) {
        errorHandler(e.message)
      }
    }
  })
}, 500, {
  leading: true
})


export { post, axiosInstance, postWithAns }
